package com.zjw.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.zjw.annotation.domain.ResponseResult;
import com.zjw.annotation.domain.entity.Category;
import com.zjw.annotation.domain.vo.AllCategoryListVo;
import com.zjw.enums.AppHttpCodeEnum;
import com.zjw.exception.SystemException;
import com.zjw.service.CategoryService;
import com.zjw.utils.BeanCopyUtils;
import com.zjw.utils.WebUtils;
import io.jsonwebtoken.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/content/category")
@PreAuthorize("@Ps.hasPermission('content:category:list')")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    @GetMapping("/listAllCategory")
    public ResponseResult getCategory() {
        return categoryService.getValidCategoryList();
    }

    @GetMapping("/list")
    public ResponseResult getAllCategoryList(Long pageNum, Long pageSize) {
        return categoryService.getAllCategoryList(pageNum, pageSize);
    }

    @PostMapping
    public ResponseResult addCategory(@RequestBody Category category){
        return categoryService.addCategory(category);
    }

    @GetMapping("/{id}")
    public ResponseResult getCategory(@PathVariable Long id){
        return categoryService.getCategory(id);
    }

    @PutMapping
    public ResponseResult alterCategory(@RequestBody Category category){
        return categoryService.saveCategery(category);
    }

    @DeleteMapping("/{ids}")
    public ResponseResult delCategories(@PathVariable String ids){
        if(!Strings.hasText(ids))
            throw new SystemException(AppHttpCodeEnum.DATA_UNCOMPLETED);

        List<Long> idList = Arrays.stream(ids.split(",")).map(n -> Long.parseLong(n))
                .collect(Collectors.toList());
        return categoryService.delCategories(idList);
    }


    /**
     * 导出 Excel
     *
     * @param response 响应
     * @return {@link ResponseResult}
     */
    @GetMapping("/export")
    @PreAuthorize("@Ps.hasPermission('content:category:export')")
    public void export(HttpServletResponse response) throws IOException {
        //        获取到要导出的数据List
        //设置下载文件的请求头
        WebUtils.setDownLoadHeader("分类.xlsx",response);
        List<Category> rawList = categoryService.list(null);
        List<AllCategoryListVo> resList = BeanCopyUtils.copyList(rawList, AllCategoryListVo.class);

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("分类导出表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), AllCategoryListVo.class).autoCloseStream(Boolean.FALSE).sheet("模板")
                    .doWrite(resList);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }
}
